package com.yanyeori.framework.web.http.request.resttemplate;

import com.yanyeori.framework.web.http.request.GeneralRequestHeader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.Map;

/**
 * 实现ClientHttpRequestInterceptor接口，可以对请求进行拦截，并在其被发送至服务端之前修改请求或是增强相应的信息
 *
 * @author chenkuan
 * @since 2021/7/29
 */
public class RestClientHttpRequestInterceptor extends GeneralRequestHeader implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();

        // 设置自定义信息到header:主要是设置自行设置的token、userId等信息，以便转发到RestTemplate调用的服务
        Map<String, String> headersMap = contextsToHeadersMap(getContext());
        if (!headersMap.isEmpty()) {
            headersMap.forEach((key, value) -> {
                if (!headers.containsKey(key)) {
                    headers.add(key, value);
                }
            });
        }

        // 保证请求继续被执行
        return execution.execute(request, body);
    }
}
